package com.netty.demo.nio;

import com.netty.demo.nio.handler.ClientHandler;
import com.netty.demo.nio.handler.impl.ClientMessageReceiveHandler;
import com.netty.demo.nio.handler.impl.LoginResponseHandler;
import com.netty.demo.protocol.packet.PacketDecoder;
import com.netty.demo.protocol.packet.PacketEncoder;
import com.netty.demo.utils.ConsoleUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class NettyClient {
    private static int MAX_RETRY = 5;

    public static void main(String[] args) throws InterruptedException{
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true);
        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch){
//                ch.pipeline().addLast(new StringEncoder());
//                ch.pipeline().addLast(new StringDecoder());
//                ch.pipeline().addLast(new FirstClientChannleHandler());
//                ch.pipeline().addLast(new ClientHandler());
                ch.pipeline().addLast(new PacketDecoder());
                ch.pipeline().addLast(new LoginResponseHandler());
                ch.pipeline().addLast(new ClientMessageReceiveHandler());
                ch.pipeline().addLast(new PacketEncoder());
            }
        });

        Channel channel = connect(bootstrap, "127.0.0.1", 1000, MAX_RETRY).channel();

//        while (true) {
//            channel.writeAndFlush(new Date() + ": hello world!");
//            Thread.sleep(2000);
//        }
    }


    private static ChannelFuture connect(Bootstrap bootstrap, String host, int port, int retry){
        return bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接成功!");
                Channel channel = ((ChannelFuture) future).channel();
                ConsoleUtils.startClientConsoleThread(channel);
            } else if (retry == 0) {
                System.err.println("重试次数已用完，放弃连接！");
            } else {
                // 第几次重连
                int order = (MAX_RETRY - retry) + 1;
                // 本次重连的间隔
                int delay = 1 << order;
                System.err.println(new Date() + ": 连接失败，第" + order + "次重连……");
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit
                        .SECONDS);
            }
        });
    }
}
